import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/UserProvider.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../utils/Global.dart';
class Profile extends StatefulWidget {
  const Profile({super.key});

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  final picker = ImagePicker();
  var _image;
  bool _isEditable = false;
  String _initText = '';
  // 用来保留文本框内容
  late TextEditingController _editingController;
 final TextEditingController _userNameController = new TextEditingController();
  @override
  void initState() {
    // 初始化必须放在initState中 使用 G.getCurrentContext()?.watch<UserProvider> 获取到上下文
    _initText = G.getCurrentContext()?.watch<UserProvider>().userInfo['username'];
    _editingController = TextEditingController(text: _initText);
  }
  Future _takePhoto() async {
    // 取摄像头的照片
    final pickedFile = await picker.pickImage(source: ImageSource.camera);
    setState(() {
      if(pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('no image');
      }
    });
  }
  // 相册中选取
  Future _openGallery() async {
    // 取相册的照片
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    setState(() {
      if(pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('no image');
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text('个人资料'),
        centerTitle: true,
      ),
      body: Container(
        child: Column(children: [
          ListTile(
            title: Text('头像'),
            trailing: 
              _image == null ? (userProvider.userInfo['portrait'] == null ?
                Icon(
                  Icons.supervised_user_circle_rounded,
                  size: 50
                ) :
                Image.network(
                  userProvider.userInfo['portrait'] ?? '',
                  fit: BoxFit.cover
                ) 
              ):
               Image.file( _image)
            ,
            onTap: () {
              showModalBottomSheet(
                context: context, 
                builder: (BuildContext context) {
                  return renderBottomSheet(context);
                }
              );
            },
          ),
          ListTile(
            title: Text('昵称'),
            trailing: renderUserName(),
          ),
        ],)
      ),
    );
  }

  Widget renderUserName() {
    if(_isEditable) {
      return Container(
        width: 100,
        child: TextField(
          controller: _editingController,
          autofocus: true,
          onSubmitted: (val) {
            setState(() {
              _initText = val;
              _isEditable = false;
            });
          },
        ),
      );
    } else {
      return InkWell(
        onTap: () {
          setState(() {
            _isEditable = true;
          });
        },
        child: Text(
          _initText,
          style: TextStyle(
            fontSize: 18.0
          ),
        ),
      );
    }
  }

  Widget renderBottomSheet(BuildContext context) {
    return Container(
      height: 160,
      child: Column(children: [
        InkWell(
          onTap: () {
            _takePhoto();
            G.router?.pop(context);
          },
          child: Container(
            child: Text('拍照'),
            height: 50,
            alignment: Alignment.center,
          ),
        ),
        InkWell(
          onTap: () {
            _openGallery();
            G.router?.pop(context);
          },
          child: Container(
            child: Text('从相册选取'),
            height: 50,
            alignment: Alignment.center,
          ),
        ),
        Container(
          height: 10,
          color: Colors.grey[200],
        ),
        InkWell(
          onTap: () {
            G.router?.pop(context);
          },
          child: Container(
            child: Text('取消'),
            height: 50,
            alignment: Alignment.center,
          ),
        )
      ]),
    );
  }
}